<template>
  <div class="app-container">
    <el-row style="margin-bottom:10px">
      <el-col :span="20">
        <div>自动更新</div>
      </el-col>
      <el-col :span="4" v-show="autoUpdate">
        <el-button size="small" @click="addAuto">添加自动更新</el-button>
      </el-col>
    </el-row>
    <el-table 
    :data="list"
    :span-method="arraySpanMethod" 
    v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" prop="updatedAt" label="最近更新时间" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.updatedAt | dateformat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新版本">
        <template slot-scope="scope">
          {{`${scope.row.fileName}(size:${scope.row.size},version_code:${scope.row.versionCode},md5:${scope.row.md5})`}}
        </template>
      </el-table-column>
      <el-table-column label="强制更新版本" width="110" align="center">
        <template slot-scope="scope">
          {{scope.row.forceVersionCode == 0 ? '--' : scope.row.forceVersionCode}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="small" @click="updateAuto(scope.row)">更新
          </el-button>
          <el-button v-if="scope.row.status == 1" size="small" @click="stopVersion(scope.row)">暂停</el-button>
          <el-button v-else size="small" @click="recoverVersion(scope.row)">恢复</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin:20px 0">
      <el-col :span="20">
        <div>按渠道更新</div>
      </el-col>
      <el-col :span="4">
        <el-button size="small"  @click="addUpdate">添加渠道更新</el-button>
      </el-col>
    </el-row>
    <el-table 
    :data="list2"
    v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row> 
      <el-table-column label="渠道名称" width="150" align="center">
        <template slot-scope="scope">
          {{scope.row.channelName }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updatedAt" label="最近更新时间" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.updatedAt | dateformat('YYYY-MM-DD HH:mm')  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新版本">
        <template slot-scope="scope">
           <template v-if="scope.row.channelId === 7">
             {{`${scope.row.versionName }`}}
           </template>
           <template v-else>
              <template v-if="scope.row.url == ''">--</template>
              <template v-else>
                {{`${scope.row.fileName}(size:${scope.row.size},version_code:${scope.row.versionCode},md5:${scope.row.md5})`}}
              </template>
           </template>
        </template>
      </el-table-column>
      <el-table-column label="强制更新版本" width="110" align="center">
        <template slot-scope="scope">
          {{scope.row.forceVersionCode == 0 ? '--' : scope.row.forceVersionCode}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="small" @click="updateAuto(scope.row)">更新
          </el-button>
          <el-button v-if="scope.row.status == 1" size="small" @click="stopVersion(scope.row)">暂停</el-button>
          <el-button v-else size="small" @click="recoverVersion(scope.row)">恢复</el-button>
           <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="渠道更新" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="渠道名称："  prop="channelId" label-width="120px" v-show="form.channelId !== 0">
          <template v-if="type === 'add'">
            <el-select v-model="form.channelId" placeholder="请选择渠道名称">
              <el-option v-for="(item,index) in channelsOther" :key="index" :label="item.channelShowName" :value="item.channelId"></el-option>
            </el-select>
          </template>
          <template v-else>
            <el-select v-model="form.channelId" disabled>
              <el-option v-for="(item,index) in channels" :key="index" :label="item.channelShowName" :value="item.channelId"></el-option>
            </el-select>
          </template>
        </el-form-item>
        <template v-if="form.channelId == 7">
          <el-form-item label="版本号：" label-width="120px">
              <el-input v-model="form.versionName" style="max-width:120px" maxlength="10"></el-input>
          </el-form-item>
          <el-form-item label="是否可用：" label-width="120px">
             <el-radio v-model="form.status" :label="1">是</el-radio>
             <el-radio v-model="form.status" :label="0">否</el-radio>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="选择文件：" label-width="120px">
              <el-upload
                ref="upload"
                :headers="headers"
                action="/tools/oss/uploadApk"
                :accept="'.apk'"
                :before-upload="onBeforeUpload"
                :on-progress="handleProgress"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                :file-list="fileList"
                :limit="2">
                <div slot="tip" class="el-upload__tip">只支持上传apk文件</div>
                <el-button size="small" type="primary">请选择一个文件</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="填写更新日志：" label-width="120px">
              <el-input v-model="form.updateLog" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"></el-input>
            </el-form-item>
            <el-form-item label="强制更新版本：" label-width="120px">
              <el-input-number  v-model="form.forceVersionCode" :step="1"></el-input-number>
            </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-loading="uploadLoading" type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getInitConfig, update, delId } from '@/api/version'
import { getToken } from '@/utils/auth' // 验权

export default {
  data() {
    return {
      rules: {
        channelId: [
          { required: true, message: '请选择渠道名称', trigger: 'change' }
        ]
      },
      fileList:[],
      type:'add',
      headers:{},
      channelsOther:[],
      channels:[],
      list: [],
      list2:null,
      uploadLoading: false,
      listLoading: true,
      autoUpdate: true,
      dialogFormVisible: false,
      form: {
        id:0,
        channelId:'',
        status:1,
        channelName:'',
        updateLog:'',
        forceVersionCode:'',
        versionName:''
      }
    }
  },
  created() {
    this.getInitConfig()
  },
  mounted(){
    this.headers = { accessToken:getToken() }
  },
  methods: {
    onBeforeUpload(file){
      /*if(!file.type.includes('android')){
        this.$notify({
            title: '失败',
          message: '请上传apk文件',
          type: 'error',
          duration: 2000
        })
        return false;
      }else{
        return true;
      }*/
    },
    handleProgress(){
      this.uploadLoading = true
    },
    updateAuto(row){
      this.type = 'update'
      this.form = Object.assign({}, row)
      if(row['url'] && row['url'].length != 0){
        this.fileList = [{ name:row['url'], url:row['url'] }]
      }
      this.dialogFormVisible = true
    },
    addAuto(){
      this.type = 'add'
      this.form = {
        id:0,
        channelId:0,
        status:1,
        channelName:'',
        updateLog:'',
        forceVersionCode:'',
        versionName:''
      }
      this.fileList = []
      this.dialogFormVisible = true
    },
    addUpdate(){
      this.type = 'add'
      this.form = {
        id:0,
        channelId:'',
        status:1,
        channelName:'',
        updateLog:'',
        forceVersionCode:'',
        versionName:''
      }
      this.fileList = []
      this.dialogFormVisible = true
    },
    updateData() {
      if(this.uploadLoading){ return }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { form } = this
          const { channels } = this
          if(form['channelId'] != 0){
            form['channelName'] = channels.filter(e => e.channelId == form['channelId'])[0].channelName
          }
          if(form['versionName'] == 0){
            form['versionName'] = '--'
          }
          if(!form['forceVersionCode']){
            form['forceVersionCode'] = 0
          }
          update(form).then(response => {
            const { code } = response
            if(code == 0){
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加渠道成功',
                type: 'success',
                duration: 2000
              })
              this.fetchData()
            }
          })
        } else {
          return false
        }
      })
    },
    handleDelete(idx, row) {
      const { id, channelId } = row
      delId(id).then(response => {
        const { code } = response
        if(code == 0){
          this.$notify({
            title: '成功',
            message: '删除渠道成功',
            type: 'success',
            duration: 2000
          })
          if(channelId == 0){
            this.list = []
            this.autoUpdate = true
          }else{
            const index = this.list2.indexOf(idx)
            this.list2.splice(idx, 1)
            this.getFilterChannel(this.list2)
          }
        }else{
          this.$notify({
            title: '失败',
            message: '删除渠道失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleUploadSuccess(rst){
      const { code, data, message } = rst
      const { form } = this
      if(code == 0){
        this.form = Object.assign(form, data)
        this.fileList = [{ name:data.url, url:data.url }]
        this.uploadLoading = false
      }else{
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      if(fileList.length == 0){
        this.$refs.upload.clearFiles()
        this.form['url'] = ''
      }
    },
    recoverVersion(row){
      update({ id:row.id, status:1 }).then(response => {
        const { code } = response
        if(code == 0){
          row.status = 1
          this.$notify({
            title: '成功',
            message: '状态修改成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    stopVersion(row){
      update({ id:row.id, status:0 }).then(response => {
        const { code } = response
        if(code == 0){
          row.status = 0
          this.$notify({
            title: '成功',
            message: '状态修改成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    getInitConfig(){
      getInitConfig().then(response => {
        const { code, data:{ channels } } = response
        if(code == 0){
          this.channels = channels
          this.fetchData()
        }
      })
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 1) {
        if (columnIndex === 0) {
          return [1, 4]
        } else {
          return [0, 0]
        }
      }
    },
    fetchData() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        const { code, data } = response
        const newData = []
        if(code == 0){
          if(data.length != 0){
            data.map(e => {
              if(e.channelId == 0){
                this.list = [e, { updatedAt:`更新日志：${e.updateLog}` }]
                this.autoUpdate = false
              }else{
                newData.push(e)
              }
            })
          }
          this.list2 = newData
          this.listLoading = false
          this.getFilterChannel(newData)
        }
      })
    },
    getFilterChannel(data){
      const { channels } = this
      const channelsOther = []
      for (var i in channels) {
        var flag = false
        var k = channels[i]['channelId']
        for (var j in data) {
          if (k == data[j]['channelId']) {
            flag = true
            break
          }
        }
        if (!flag) {
          channelsOther.push(channels[i])
        }
      }
      this.channelsOther = channelsOther
      if(channelsOther.length != 0){
        this.form['channelId'] = channelsOther[0]['channelId']
      }
    }
  }
}
</script>
